<template>
  <div class="testTopic">
    <el-dialog
      title="测试题目"
      :visible.sync="showIframeDialog"
      @close="handleClose"
      width="800px"
      center
      :close-on-click-modal="false"
    >
      <iframe
        :src="iframeRouter"
        width="100%"
        frameborder="0"
        ref="iframeDom"
        class="iframe"
        :class="{ isLoad: isLoad }"
        v-if="foreignID && showIframeDialog"
      ></iframe>
      <div v-else>题组ID不存在</div>
    </el-dialog>
  </div>
</template>

<script>
import { location_QuestionBank, debounce, location } from "@/util/tool";
import { Session } from '@/util/storage/session.js'
import { mapState } from "vuex";
export default {
  data() {
    return {
      isLoad: false,
      height: 150,
      showIframeDialog: false,
    };
  },
  props: {
    iframeRouter: String,
    foreignID: Number,
    showTestTopicIframeDialog: Boolean,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getCurrGuidelineData() {
      // 通过当前任务组所在课程的编号找到任务组
      let thisgroupNoInCourse = this.$parent.courseData.taskCommitJson.filter(
        (item) => Number(item.taskGroupID) === Number(this.$parent.taskGroupID)
      );
      // 在找到的任务组中通过当前任务的任务编号找到任务
      let thistaskNoInGroup = thisgroupNoInCourse[0]?.tasks.filter(
        (titem) => Number(titem.taskID) === Number(this.$parent.taskID)
      );
      thistaskNoInGroup[0].taskGroupID = this.$parent.taskGroupID;
      return thistaskNoInGroup[0];
    },
    getIframeHeight() {
      return this.$refs.iframeDom?.clientHeight || 0;
    },
  },
  watch: {
    getIframeHeight(n) {},
    showTestTopicIframeDialog(n) {
      if (n) {
        this.showIframeDialog = n;
        if (this.foreignID)
          this.$nextTick(() => {
            this.listenIframeOnload();
          });
      }
    },
  },
  methods: {
    handleClose() {
      this.$emit("handleTestTopicIframeClose");
    },
    /**
     * @description 监听iframe加载完成
     */
    listenIframeOnload() {
      const that = this;
      const iframe = this.$refs.iframeDom;
      // 处理兼容行问题
      if (iframe.attachEvent) {
        iframe.attachEvent("onload", function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        });
      } else {
        iframe.onload = function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        };
      }
    },
    /**
     * otherWindow.postMessage(message, targetOrigin, [transfer]);
     * https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
     * @description 向iframe发送消息
     */
    async sendData(dom) {
     let userInfoCookie = null;
      const res = await Session.get('userInfo', true)
      userInfoCookie = res;
      if (!userInfoCookie)
        return this.$antdMessage.error({
          content: "身份信息已过期！",
        });
      this.isLoad = false;
      const gitem = this.$parent.gitem;
      const taskDetail = {
        guidelineResults: {},
      };
      taskDetail.guidelineResults[gitem.guidelineID] = gitem;
      let params = Object.assign({
        cookie: null,
        userInfo: this.userInfo,
        isStudy: true,
        taskDetail: taskDetail,
        currGuidelineID: gitem.guidelineID,
        testMode: true,
        iframeID: +new Date() + "" || "defaultIframeID",
      });
      dom.contentWindow.postMessage(
        JSON.stringify(params),
        location_QuestionBank(window)
      );
      // dom.contentWindow.postMessage(
      //   JSON.stringify(params),
      //   "http://localhost:3000/"
      // );
      window.addEventListener(
        "message",
        (event) => {
          // Do we trust the sender of this message?  (might be
          // different from what we originally opened, for example).
          if (
            event.origin !== location(window) &&
            event.origin !== "http://localhost:3000"
          )
            return;
          const data = JSON.parse(event?.data);
          if (data.iframeID == params.iframeID) {
            // let iframeHeight = JSON.parse(event?.data)?.iframeHeight;
            // this.height = iframeHeight;
          }
          // this.debounce(iframeHeight);
        },
        false
      );
    },
    debounce: debounce(function (e) {
      this.height = e;
    }, 100),
  },
  mounted() {},
};
</script>

<style lang="stylus" scoped>
.iframe {
  max-width: 779px;
  height: 80vh;
}

.isLoad {
  height: 100%;
}
</style>